package com.ruoyi.web.controller.module.event;

import java.util.ArrayList;
import java.util.List;
import java.util.Arrays;

import cn.hutool.core.util.StrUtil;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.utils.PageUtils;
import com.ruoyi.common.utils.QRCodeUtilEx;
import com.ruoyi.common.utils.file.FileUploadUtils;
import com.ruoyi.system.domain.module.estate.Estate;
import com.ruoyi.system.domain.module.event.EventCleanArea;
import com.ruoyi.system.domain.module.event.EventPatrolPoint;
import com.ruoyi.system.domain.module.event.EventPlanTaskInfo;
import com.ruoyi.system.domain.module.property.Property;
import com.ruoyi.system.domain.module.survey.Survey;
import com.ruoyi.system.service.module.estate.IEstateBuildFloorService;
import com.ruoyi.system.service.module.estate.IEstateBuildService;
import com.ruoyi.system.service.module.estate.IEstateService;
import com.ruoyi.system.service.module.event.IEventCleanAreaService;
import com.ruoyi.system.service.module.event.IEventPlanTaskInfoService;
import com.ruoyi.system.service.module.property.IPropertyService;
import com.ruoyi.system.service.module.survey.ISurveyService;
import com.ruoyi.system.service.system.ISysUserService;
import com.ruoyi.web.controller.common.BaseController;
import lombok.RequiredArgsConstructor;
import javax.validation.constraints.*;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.validation.annotation.Validated;
import com.ruoyi.common.annotation.RepeatSubmit;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.validate.AddGroup;
import com.ruoyi.common.core.validate.EditGroup;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

/**
 * 保洁、绿化区域：添加保洁计划选择Controller
 *
 * @author ruoyi
 * @date 2023-12-26
 */
@Validated
@Api(value = "保洁、绿化区域：添加保洁计划选择控制器", tags = {"保洁、绿化区域：添加保洁计划选择管理"})
@RequiredArgsConstructor(onConstructor_ = @Autowired)
@RestController
@RequestMapping("/module/event/clean/area")
public class EventCleanAreaController extends BaseController {

    private final IEventCleanAreaService eventCleanAreaService;
	private final IPropertyService propertyService;
	private final IEstateService estateService;
	private final ISysUserService sysUserService;
	private final ISurveyService surveyService;
	private final IEstateBuildService estateBuildService;

	private final IEstateBuildFloorService estateBuildFloorService;
	private final IEventPlanTaskInfoService eventPlanTaskInfoService;
	@Value("${ruoyi.profile}")
	private String uploadPath;

	@Value("${ruoyi.imgUrl}")
	private String imgUrl;

    /**
     * 查询保洁、绿化区域：添加保洁计划选择列表
     */
    @ApiOperation("查询保洁、绿化区域：添加保洁计划选择列表")
    @PreAuthorize("@ss.hasPermi('module:cleanArea:list')")
    @GetMapping("/list")
    public TableDataInfo<EventCleanArea> list(@Validated EventCleanArea eventCleanArea) {
		SysUser sysUser = getUser();
		QueryWrapper<EventCleanArea> qw = new QueryWrapper<>();
		//用户类型 0 - 系统管理员  1 - 平台管理员 2 - 物业管理员  3 - 小区管理员
		if(sysUser.getUserType() == 2){
			qw.eq("property_id",sysUser.getPropertyId());
			if (sysUser.getEstateId()!=null){
				qw.eq("estate_id",sysUser.getEstateId());
			}
		} else if(sysUser.getUserType() == 3){
			qw.eq("estate_id",sysUser.getEstateId());
		}else{
			if(eventCleanArea.getPropertyId() != null){
				qw.eq("property_id",eventCleanArea.getPropertyId());
			}
			if(eventCleanArea.getEstateId() != null){
				qw.eq("estate_id",eventCleanArea.getEstateId());
			}
		}
		if (eventCleanArea.getAreaType()!=null){
			qw.eq("area_type",eventCleanArea.getAreaType());
		}else {
			qw.ne("area_type",3);
		}
		TableDataInfo<EventCleanArea> td = PageUtils.buildDataInfo(eventCleanAreaService.page(PageUtils.buildPage(),qw));
        List<EventCleanArea> list = td.getRows();
		for (EventCleanArea area : list){

			if(StrUtil.isNotEmpty(area.getQrCode())){
				area.setQrCode(imgUrl + area.getQrCode());
			}

			if (area.getPropertyId()!=null){
				Property property = propertyService.findById(area.getPropertyId());
				if (property!=null){
					area.setPropertyName(property.getPropertyName());
				}
			}
			if (area.getEstateId()!=null){
				Estate estate = estateService.findById(area.getEstateId());
				if (estate!=null){
					area.setEstateName(estate.getEstateName());
				}
			}
			if (area.getSurveyStandardId()!=null){
				Survey survey = surveyService.getById(area.getSurveyStandardId());
				if (survey!=null){
					area.setSurveyName(survey.getQuestionTitle());
					area.setSurveyInfo(survey.getSurveyInfo());
				}
			}

		}
        return td;
    }

    /**
     * 导出保洁、绿化区域：添加保洁计划选择列表
     */
    @ApiOperation("导出保洁、绿化区域：添加保洁计划选择列表")
    @PreAuthorize("@ss.hasPermi('module:cleanArea:export')")
    @Log(title = "保洁、绿化区域：添加保洁计划选择", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public AjaxResult<EventCleanArea> export(@Validated EventCleanArea eventCleanArea) {
        List<EventCleanArea> list = eventCleanAreaService.list();
        ExcelUtil<EventCleanArea> util = new ExcelUtil<EventCleanArea>(EventCleanArea.class);
        return util.exportExcel(list, "保洁、绿化区域：添加保洁计划选择");
    }

    /**
     * 获取保洁、绿化区域：添加保洁计划选择详细信息
     */
    @ApiOperation("获取保洁、绿化区域：添加保洁计划选择详细信息")
    @PreAuthorize("@ss.hasPermi('module:cleanArea:query')")
    @GetMapping("/{id}")
    public AjaxResult<EventCleanArea> getInfo(@NotNull(message = "主键不能为空") @PathVariable("id") Integer id) {
        EventCleanArea eventCleanArea = eventCleanAreaService.getById(id);
//		if(eventCleanArea != null){
//			if(StrUtil.isNotEmpty(eventCleanArea.getQrCode())){
//				eventCleanArea.setQrCode(imgUrl + eventCleanArea.getQrCode());
//			}
//			String[] arrays = eventCleanArea.getAreaRange().split(",");
//			eventCleanArea.setAreas(arrays);
//		}
//		QueryWrapper<EventCleanAreaInfo> qw = new QueryWrapper<>();
//		qw.eq("area_id",id);
//		List<EventCleanAreaInfo> list = eventCleanAreaInfoService.list(qw);
//		if (list.size()>0){
//			EventCleanAreaInfo info = new EventCleanAreaInfo();
//			List<Integer> floorIds = new ArrayList<>();
////			for (EventCleanAreaInfo list1:list){
////				info.setBuildId(list1.getBuildId());
////				if (list1.getFloorId()!=null){
////					floorIds.add(list1.getFloorId().intValue());
////				}
////			}
////			info.setFloorIds(floorIds.toArray(new Integer[list.size()]));
//			eventCleanArea.setAreaInfo(info);
//		}
        return AjaxResult.success(eventCleanArea);
    }


	/**
	 * 修改巡检设备状态
	 */
	@ApiOperation("修改保洁点")
	@PreAuthorize("@ss.hasPermi('module:patrolPoint:edit')")
	@Log(title = "巡更点", businessType = BusinessType.UPDATE)
	@RepeatSubmit
	@PutMapping("/updateState")
	public AjaxResult<Void> editState(@Validated(EditGroup.class) @RequestBody EventCleanArea eventCleanArea) {
		EventCleanArea areas = eventCleanAreaService.getById(eventCleanArea.getId());
		areas.setState(eventCleanArea.getState());
		//查询所有巡更设备info
		if (eventCleanArea.getState()==0){
			QueryWrapper<EventPlanTaskInfo> qw = new QueryWrapper<>();
			qw.eq("target_type",eventCleanArea.getType());
			qw.eq("state",0);
			qw.eq("target_id",eventCleanArea.getId());
			List<EventPlanTaskInfo> infos = eventPlanTaskInfoService.list(qw);
			for (EventPlanTaskInfo info:infos){
				info.setState(3L);
				eventPlanTaskInfoService.updateById(info);
			}
		}
		if (eventCleanArea.getState()==1){
			QueryWrapper<EventPlanTaskInfo> qw = new QueryWrapper<>();
			qw.eq("target_type",eventCleanArea.getType());
			qw.eq("state",3);
			qw.eq("target_id",eventCleanArea.getId());
			List<EventPlanTaskInfo> infos = eventPlanTaskInfoService.list(qw);
			for (EventPlanTaskInfo info:infos){
				info.setState(0L);
				eventPlanTaskInfoService.updateById(info);
			}
		}
		return toAjax(eventCleanAreaService.updateById(areas) ? 1 : 0);
	}


	/**
     * 新增保洁、绿化区域：添加保洁计划选择
     */
    @ApiOperation("新增保洁、绿化区域：添加保洁计划选择")
    @PreAuthorize("@ss.hasPermi('module:cleanArea:add')")
    @Log(title = "保洁、绿化区域：添加保洁计划选择", businessType = BusinessType.INSERT)
    @RepeatSubmit
    @PostMapping()
    public AjaxResult<Void> add(@Validated(AddGroup.class) @RequestBody EventCleanArea eventCleanArea) {
//		SysUser sysUser = getUser();
//		eventCleanArea.setCreateBy(Math.toIntExact(sysUser.getUserId()));
//		String str = "";
//		if (eventCleanArea.getAreas()!=null){
//			for (int i=0;i<eventCleanArea.getAreas().length;i++){
//				str += eventCleanArea.getAreas()[i];
//				if (i != eventCleanArea.getAreas().length-1){
//					str+=",";
//				}
//			}
//			eventCleanArea.setAreaRange(str);
//		}
		boolean bl = eventCleanAreaService.save(eventCleanArea);
		if(bl){
			try{
				String fileName = "clean_area_qr_" + eventCleanArea.getId() + ".jpg";
				String content = "https://www.caihengyun.com/wxmini/area/info?id=" + eventCleanArea.getId();
				int upload_type = FileUploadUtils.TYPE_CLEAN_AREA;
				System.out.println("content:  "+ content);
				String img_key = FileUploadUtils.getUploadPrefix(upload_type) + fileName;
				QRCodeUtilEx.createQrCodeImg(content, eventCleanArea.getAreaTitle(), null,
					uploadPath +"/"+img_key, true, fileName, upload_type);
				eventCleanArea.setQrCode(img_key);
				eventCleanAreaService.updateById(eventCleanArea);

			}catch (Exception ex){
				ex.printStackTrace();
			}
//			if (eventCleanArea.getAreaInfo()!=null){
//				EventCleanAreaInfo areaInfo = eventCleanArea.getAreaInfo();
//				areaInfo.setAreaId(eventCleanArea.getId());
//				if (areaInfo.getBuildId()!=null){
//					EstateBuild build = estateBuildService.findById(areaInfo.getBuildId());
//					if (build!=null){
//						areaInfo.setBuildId(build.getId());
//						if (build.getBuildType()!=null){
//							areaInfo.setBuildType(build.getBuildType());
//						}
//						if (build.getSort()!=null){
//							areaInfo.setSort(build.getSort());
//						}
//						if (areaInfo.getFloorIds().length==0){
//							if (areaInfo.getBuildType()==0){
//								QueryWrapper<EstateBuildFloor> qw = new QueryWrapper<>();
//								qw.eq("build_id",build.getId());
//								List<EstateBuildFloor> floors = estateBuildFloorService.list(qw);
//								if (floors.size()>0){
//									for (EstateBuildFloor floor : floors){
//										areaInfo.setAreaName(floor.getFloorName());
//										areaInfo.setFloorId(floor.getId());
//										areaInfo.setId(null);
//										eventCleanAreaInfoService.save(areaInfo);
//									}
//								}
//								return toAjax(bl ? 1 : 0);
//							}else {
//								areaInfo.setAreaName(build.getBuildName());
//								eventCleanAreaInfoService.save(areaInfo);
//								return toAjax(bl ? 1 : 0);
//							}
//						}
//						if (areaInfo.getFloorIds().length>0){
//							for (Integer area:areaInfo.getFloorIds()){
//								EstateBuildFloor floor = estateBuildFloorService.findById(area);
//								if (floor!=null){
//									areaInfo.setAreaName(floor.getFloorName());
//									areaInfo.setFloorId(floor.getId());
//									areaInfo.setId(null);
//									eventCleanAreaInfoService.save(areaInfo);
//								}
//							}
//						}
//
//					}
//				}
//			}
		}
        return toAjax(bl ? 1 : 0);
    }


	/**
	 * 重置二维码
	 */
	@Log(title = "重置二维码")
	@PostMapping("/resetQrCode")
	@ResponseBody
	@PreAuthorize("@ss.hasPermi('module:cleanArea:edit')")
	public AjaxResult<Void> resetQrCode(@RequestBody EventCleanArea eventCleanArea) {
		if(eventCleanArea.getId()!=null){
			try{
				eventCleanArea = eventCleanAreaService.getById(eventCleanArea.getId());
				if(eventCleanArea!= null){
					String fileName = "clean_area_qr_" + eventCleanArea.getId() + ".jpg";
					String content = "https://www.caihengyun.com/wxmini/area/info?id=" + eventCleanArea.getId();
					int upload_type = FileUploadUtils.TYPE_CLEAN_AREA;
					System.out.println("content:  "+ content);
					String img_key = FileUploadUtils.getUploadPrefix(upload_type) + fileName;
					QRCodeUtilEx.createQrCodeImg(content, eventCleanArea.getAreaTitle(), null, uploadPath +"/"+img_key, true, fileName, upload_type);
					eventCleanArea.setQrCode(img_key);
				}
			}catch (Exception ex){
				ex.printStackTrace();
			}
			if (eventCleanAreaService.updateById(eventCleanArea)) {
				return AjaxResult.success();
			}
		}
		return AjaxResult.error();
	}

    /**
     * 修改保洁、绿化区域：添加保洁计划选择
     */
    @ApiOperation("修改保洁、绿化区域：添加保洁计划选择")
    @PreAuthorize("@ss.hasPermi('module:cleanArea:edit')")
    @Log(title = "保洁、绿化区域：添加保洁计划选择", businessType = BusinessType.UPDATE)
    @RepeatSubmit
    @PutMapping()
    public AjaxResult<Void> edit(@Validated(EditGroup.class) @RequestBody EventCleanArea eventCleanArea) {
//		String str = "";
//		for (int i=0;i<eventCleanArea.getAreas().length;i++){
//			str+=eventCleanArea.getAreas()[i];
//			if (i!=eventCleanArea.getAreas().length-1){
//				str+=",";
//			}
//		}
//		eventCleanArea.setAreaRange(str);
//		QueryWrapper<EventCleanAreaInfo> qw1 = new QueryWrapper<>();
//		qw1.eq("area_id",eventCleanArea.getId());
//		List<EventCleanAreaInfo> list = eventCleanAreaInfoService.list(qw1);
//		if (list.size()>0){
//			for (EventCleanAreaInfo list1:list){
//				eventCleanAreaInfoService.removeById(list1.getId());
//			}
//		}
//		if (eventCleanArea.getAreaInfo()!=null){
//			EventCleanAreaInfo areaInfo = eventCleanArea.getAreaInfo();
//			areaInfo.setAreaId(eventCleanArea.getId());
//			if (areaInfo.getBuildId()!=null){
//				EstateBuild build = estateBuildService.findById(areaInfo.getBuildId());
//				if (build!=null){
//					areaInfo.setBuildId(build.getId());
//					if (build.getBuildType()!=null){
//						areaInfo.setBuildType(build.getBuildType());
//					}
//					if (build.getSort()!=null){
//						areaInfo.setSort(build.getSort());
//					}
//					if (areaInfo.getFloorIds().length==0){
//						if (areaInfo.getBuildType()==0){
//							QueryWrapper<EstateBuildFloor> qw = new QueryWrapper<>();
//							qw.eq("build_id",build.getId());
//							List<EstateBuildFloor> floors = estateBuildFloorService.list(qw);
//							if (floors.size()>0){
//								for (EstateBuildFloor floor : floors){
//									areaInfo.setAreaName(floor.getFloorName());
//									areaInfo.setFloorId(floor.getId());
//									areaInfo.setId(null);
//									eventCleanAreaInfoService.save(areaInfo);
//								}
//							}
//							return toAjax(1);
//						}else {
//							areaInfo.setAreaName(build.getBuildName());
//							eventCleanAreaInfoService.save(areaInfo);
//							return toAjax(1);
//						}
//					}
//					if (areaInfo.getFloorIds().length>0){
//						for (Integer area:areaInfo.getFloorIds()){
//							EstateBuildFloor floor = estateBuildFloorService.findById(area);
//							if (floor!=null){
//								areaInfo.setAreaName(floor.getFloorName());
//								areaInfo.setFloorId(floor.getId());
//								areaInfo.setId(null);
//								eventCleanAreaInfoService.save(areaInfo);
//							}
//						}
//					}
//
//				}
//			}
//		}

        return toAjax(eventCleanAreaService.updateById(eventCleanArea) ? 1 : 0);
    }

    /**
     * 删除保洁、绿化区域：添加保洁计划选择
     */
    @ApiOperation("删除保洁、绿化区域：添加保洁计划选择")
    @PreAuthorize("@ss.hasPermi('module:cleanArea:remove')")
    @Log(title = "保洁、绿化区域：添加保洁计划选择" , businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult<Void> remove(@NotEmpty(message = "主键不能为空")  @PathVariable Integer[] ids) {
//		for (Integer id:ids){
//			QueryWrapper<EventCleanAreaInfo> qw1 = new QueryWrapper<>();
//			qw1.eq("area_id",id);
//			List<EventCleanAreaInfo> list = eventCleanAreaInfoService.list(qw1);
//			if (list.size()>0){
//				for (EventCleanAreaInfo list1:list){
//					eventCleanAreaInfoService.removeById(list1.getId());
//				}
//			}
//		}
        return toAjax(eventCleanAreaService.removeByIds(Arrays.asList(ids)) ? 1 : 0);
    }
}
